package handlers

import (
	"encoding/json"
	"game-hub/cache"
	"game-hub/models"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	name := c.PostForm("name")
	types := c.PostForm("types")
	counts, _ := strconv.Atoi(c.PostForm("counts"))
	user_id, _ := strconv.Atoi(c.PostForm("user_id"))
	if name == "" || types == "" || counts == 0 || user_id == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	game := models.Game{
		Name:   name,
		Types:  types,
		Counts: counts,
		UserId: user_id,
	}
	err := models.DB.Create(&game).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "add_err_" + name
	cache.Rdb.Get(cache.Ctx, redis_key)
	models.DB.Find(&game)
	marshal, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}

func List(c *gin.Context) {
	var game []models.Game
	err := models.DB.Find(&game).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "List_"
	cache.Rdb.Get(cache.Ctx, redis_key)
	models.DB.Find(&game)
	marshal, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": game,
	})
	return
}

func Find(c *gin.Context) {
	id := c.Query("id")
	var game models.Game
	err := models.DB.Where("id=?", id).Find(&game).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "find_" + id
	cache.Rdb.Get(cache.Ctx, redis_key)
	models.DB.Find(&game)
	marshal, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": game,
	})
	return
}

func Down(c *gin.Context) {

	id := c.Query("id")
	var game models.Game
	err := models.DB.Where("id=?", id).Find(&game).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "find_" + id
	cache.Rdb.Get(cache.Ctx, redis_key)
	models.DB.Find(&game)
	marshal, _ := json.Marshal(game)
	cache.Rdb.Set(cache.Ctx, redis_key, marshal, time.Hour*2)
	game.Counts++
}
